package com.copyctrl.campus.portal.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.constant.HttpConstant;
import com.copyctrl.campus.common.constant.RedisConstant;
import com.copyctrl.campus.common.constant.Status;
import com.copyctrl.campus.common.domain.User;
import com.copyctrl.campus.common.exception.DataBaseException;
import com.copyctrl.campus.common.model.ApiResponse;
import com.copyctrl.campus.portal.service.GoodsService;
import com.copyctrl.model.CampGoods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    GoodsService service;

    @Autowired
    StringRedisTemplate redisTemplate;

    @PostMapping("/{goods}")
    public ApiResponse add(@PathVariable String goods,HttpServletRequest request) {
        CampGoods campGoods = JSONUtil.toBean(goods, CampGoods.class);
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取openid,转换成id存入redis中
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        Integer id=user.getId();
        campGoods.setUid(id);
        int i=service.add(campGoods);
        return i==1?ApiResponse.ofSuccess("ok"):ApiResponse.ofFailure("发布失败请联系管理员");
    }

    @DeleteMapping("/{goods}")
    public ApiResponse delete(@PathVariable String goods) {
        CampGoods campGoods = JSONUtil.toBean(goods, CampGoods.class);
        int i=service.delete(campGoods);
        return i==1?ApiResponse.ofSuccess("ok"):ApiResponse.ofFailure("发布失败请联系管理员");
    }

    @PutMapping("/{goods}")
    public ApiResponse update(@PathVariable String goods) {
        CampGoods campGoods = JSONUtil.toBean(goods, CampGoods.class);
        int i=service.update(campGoods);
        return i==1?ApiResponse.ofSuccess("ok"):ApiResponse.ofFailure("发布失败请联系管理员");
    }

    @GetMapping("/all")
    public ApiResponse findAll(HttpServletRequest request) {
        String openid = request.getHeader(HttpConstant.USER);
        //从请求头中获取openid,转换成id存入redis中
        String userJson = redisTemplate.opsForValue().get(RedisConstant.USER_KEY + openid);
        User user = JSONUtil.toBean(userJson, User.class);
        Integer id=user.getId();
        return ApiResponse.ofSuccess(service.findAll(id));
    }
    @GetMapping("/{id}")
    public ApiResponse find(@PathVariable Integer id) {
        return ApiResponse.ofSuccess(service.findByUser(id));
    }
}
